import React, { createContext, useContext, useState, useCallback } from 'react';
import avatar from '../assets/avatar.png';

// 创建 Context
const UserContext = createContext();

// Provider 组件
export const UserProvider = ({ children }) => {
    // 状态定义
    const [user, setUser] = useState({
        id: null,
        name: '',
        avatarUrl: avatar, // 默认头像
        isAuthenticated: false
    });

    // 更新用户信息
    const updateUser = useCallback((userData) => {
        setUser(prev => ({
            ...prev,
            ...userData
        }));
    }, []);

    // 设置用户认证状态
    const setAuthenticated = useCallback((isAuthenticated) => {
        setUser(prev => ({
            ...prev,
            isAuthenticated
        }));
    }, []);

    // 更新用户头像
    const updateAvatar = useCallback((avatarUrl) => {
        setUser(prev => ({
            ...prev,
            avatarUrl
        }));
    }, []);

    // 清除用户信息
    const clearUser = useCallback(() => {
        setUser({
            id: null,
            name: '',
            avatarUrl: avatar,
            isAuthenticated: false
        });
    }, []);

    // Context 值
    const value = {
        user,
        updateUser,
        setAuthenticated,
        updateAvatar,
        clearUser
    };

    return (
        <UserContext.Provider value={value}>
            {children}
        </UserContext.Provider>
    );
};

// 自定义 Hook
export const useUser = () => {
    const context = useContext(UserContext);
    if (!context) {
        throw new Error('useUser must be used within a UserProvider');
    }
    return context;
}; 